package ynu.edu.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.edu.entities.Address;
import ynu.edu.entities.BaseResponse;
import ynu.edu.repository.AddressRepository;
import ynu.edu.service.AddressService;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class AddressServiceImpl implements AddressService {

    private static final Logger logger = LoggerFactory.getLogger(AddressServiceImpl.class);

    @Autowired
    private AddressRepository addressRepository;

    @Override
    public BaseResponse<List<Address>> listAddressByUserId(String userId) {
        logger.info("开始查询用户地址列表，userId: {}", userId);
        try {
            // 检查userId是否为空或无效
            if (userId == null || userId.trim().isEmpty()) {
                logger.error("查询用户地址列表失败：userId为空或无效");
                return new BaseResponse<>(400, "用户ID不能为空", null);
            }
            
            logger.info("执行数据库查询，查询用户ID: {}", userId);
            List<Address> addresses = addressRepository.findByUserIdOrderByIsDefaultDesc(userId);
            
            // 记录查询结果
            if (addresses == null) {
                logger.warn("查询结果为null，userId: {}", userId);
                return new BaseResponse<>(200, "获取地址列表成功", null);
            } else {
                logger.info("查询到用户地址数量: {}, userId: {}", addresses.size(), userId);
                // 记录每个地址的基本信息，帮助调试
                for (int i = 0; i < addresses.size(); i++) {
                    Address addr = addresses.get(i);
                    logger.debug("地址[{}]: ID={}, 联系人={}, 地址={}, 是否默认={}", 
                        i, addr.getDaId(), addr.getContactName(), addr.getAddress(), addr.getIsDefault());
                }
            }
            
            return new BaseResponse<>(200, "获取地址列表成功", addresses);
        } catch (Exception e) {
            logger.error("查询用户地址列表出错，userId: {}, 错误类型: {}, 错误信息: {}", 
                userId, e.getClass().getName(), e.getMessage(), e);
            throw e;
        }
    }

    @Override
    public Address getAddressById(Integer daId, String userId) {
        logger.debug("开始查询地址详情，daId: {}, userId: {}", daId, userId);
        try {
            Address address = addressRepository.findByDaIdAndUserId(daId, userId);
            logger.debug("查询到地址: {}", address);
            return address;
        } catch (Exception e) {
            logger.error("查询地址详情出错，daId: {}, userId: {}, 错误信息: {}", daId, userId, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public BaseResponse<Address> saveAddress(Address address) {
        logger.debug("开始保存地址，address: {}", address);
        try {
            // 如果是设置为默认地址，则先将该用户的所有地址设为非默认
            if (address.getIsDefault() != null && address.getIsDefault() == 1) {
                logger.debug("设置为默认地址，先清除其他默认地址，userId: {}", address.getUserId());
                addressRepository.clearDefaultAddress(address.getUserId());
            }
            // 如果未设置默认标志，默认为非默认
            if (address.getIsDefault() == null) {
                address.setIsDefault(0);
            }
            
            // 如果未设置联系人性别，默认为1（男性）
            if (address.getContactSex() == null) {
                address.setContactSex(1);
            }
            
            Address savedAddress = addressRepository.save(address);
            logger.debug("地址保存成功，savedAddress: {}", savedAddress);
            return new BaseResponse<>(200, "地址保存成功", savedAddress);
        } catch (Exception e) {
            logger.error("保存地址出错，address: {}, 错误信息: {}", address, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public BaseResponse<Address> updateAddress(Address address) {
        logger.debug("开始更新地址，address: {}", address);
        try {
            // 检查地址是否存在
            Address existingAddress = addressRepository.findByDaIdAndUserId(address.getDaId(), address.getUserId());
            if (existingAddress == null) {
                logger.warn("要更新的地址不存在，daId: {}, userId: {}", address.getDaId(), address.getUserId());
                return new BaseResponse<>(404, "地址不存在", null);
            }
            
            // 如果是设置为默认地址，则先将该用户的所有地址设为非默认
            if (address.getIsDefault() != null && address.getIsDefault() == 1) {
                logger.debug("设置为默认地址，先清除其他默认地址，userId: {}", address.getUserId());
                addressRepository.clearDefaultAddress(address.getUserId());
            }
            
            // 如果未设置联系人性别，默认为1（男性）
            if (address.getContactSex() == null) {
                address.setContactSex(1);
            }
            
            Address updatedAddress = addressRepository.save(address);
            logger.debug("地址更新成功，updatedAddress: {}", updatedAddress);
            return new BaseResponse<>(200, "地址更新成功", updatedAddress);
        } catch (Exception e) {
            logger.error("更新地址出错，address: {}, 错误信息: {}", address, e.getMessage(), e);
            throw e;
        }
    }

    @Override
    @Transactional
    public BaseResponse<Void> deleteAddress(Integer daId, String userId) {
        logger.debug("开始删除地址，daId: {}, userId: {}", daId, userId);
        try {
            // 检查地址是否存在
            Address existingAddress = addressRepository.findByDaIdAndUserId(daId, userId);
            if (existingAddress == null) {
                logger.warn("要删除的地址不存在，daId: {}, userId: {}", daId, userId);
                return new BaseResponse<>(404, "地址不存在", null);
            }
            
            addressRepository.delete(existingAddress);
            logger.debug("地址删除成功，daId: {}, userId: {}", daId, userId);
            return new BaseResponse<>(200, "地址删除成功", null);
        } catch (Exception e) {
            logger.error("删除地址出错，daId: {}, userId: {}, 错误信息: {}", daId, userId, e.getMessage(), e);
            throw e;
        }
    }
} 